import Vue from 'vue';
import Fly from 'flyio/dist/npm/wx';
// //#ifdef MP-WEIXIN
// import Fly from 'flyio/dist/npm/wx';
// //#endif
// //#ifdef APP-PLUS
// import Fly from 'flyio/dist/npm/weex';
// //#endif
// // H5版本
// //#ifdef H5
// import Fly from 'flyio/dist/npm/fly';
// //#endif

import {
	APP_KEY,
	BASE_URL
} from '@/config/index.js';
import {
	getAppSign
} from '@/utils/index.js';

const fly = new Fly;

const config = {
	timeout: '18000',
	headers: {
		'Content-Type': 'application/json',
		'appKey': APP_KEY,
	},
	parseJson: true,
	baseURL: BASE_URL,
}

fly.config = config;

fly.interceptors.request.use((request) => {
	const token = uni.getStorageSync('loginToken');
	if (token) {
		request.headers['loginToken'] = token;
	}
	// request.headers['miniAppId'] = uni.getStorageSync("miniCode");
	const sessionGenerateId = uni.getStorageSync('sessionGenerateId');
	request.headers['sessionGenerateId'] = sessionGenerateId;
	const timestamp = (new Date()).valueOf();
	request.headers['timestamp'] = timestamp;
	const appSign = getAppSign(timestamp)
	request.headers['appSign'] = appSign;
})

fly.interceptors.response.use(

	function(response) {
		const data = response.data;
		// 重新登录
		if (data.code === 102) {
			uni.redirectTo({
				url: '/pages/login/login'
			})
			// const loginStatus = uni.getStorageSync('logining');
			// if (loginStatus) {
			// 	return response
			// }
		}
		if (data.code !== 100 && data.code !== 102 && response.request.url != '/common/shop/publicKey') {
			uni.showToast({
				icon: 'none',
				title: data.msg
			})
		}
		return response
	},
	function(err) {
		uni.showToast({
			title: '网络异常',
			icon: 'none',
			duration: 2000
		});
	}
)

export function GET(url, data = {}) {
	return new Promise((resolve, reject) => {
		fly.get(url, data).then(res => {
			if (res) {
				resolve(res.data);
			}
		}).catch(err => {
			reject(err);
		})
	}).finally(() => {

	})
}

export function POST(url, data = {}) {
	return new Promise((resolve, reject) => {
		fly.post(url, data).then(res => {
			if (res) {
				resolve(res.data);
			}
		}).catch(err => {
			reject(err);
		})
	}).finally(() => {

	})
}